/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact 824069438@qq.com
 *  
 */
package org.zfes.snowy.auth.shiro.util;

import org.apache.shiro.codec.Base64;


import org.apache.shiro.codec.Hex;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.zfes.snowy.auth.AuthConsts;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

public class ShiroMD5EndecryptUtil {
	
	private  static  SecureRandomNumberGenerator randomNumberGenerator= new SecureRandomNumberGenerator();
   /**
    * 第一步--（页面加密，盐值为 userName+FrameConst.COMPASS_CREDENTIALS.pageSalt） 
    * @param userName
    * @param expectPassword
    * @return
    */
    public static String genSetp1Password(String expectPassword){
    	String page_salt=AuthConsts.COMPASS_CREDENTIALS.pageSalt;
    	String firstMd5Salt=page_salt;
    	String password_from_page= genPassword(expectPassword,firstMd5Salt,1);
    	return password_from_page;
    }
    /**
     * 第二步： 页面加密后传递后台的 第一次加密后的 密码，再进行两次md5 加密
     * @param userName
     * @param expectPassword
     * @return
     */
    public static String  genSetp2Password(String passwordAfFirstStep,String rondomSalt){
    	String encptyedPassword=genPassword(passwordAfFirstStep,rondomSalt,2);
    	return encptyedPassword;
    }
	public static String genRandomSalt(){
		return	randomNumberGenerator.nextBytes().toHex();
    }
    public static String genPassword(String password,String salt,int times){
    	String password_cipherText2= new Md5Hash(password,salt,times).toHex().toString(); 
    	return password_cipherText2;
    }

    public static void main(String[] argd){
    	
    	String pwd1=genSetp1Password("admin");
    	String salt=genRandomSalt();
    	String pwd2=genSetp2Password(pwd1,salt);
    	System.out.println(pwd1+"||"+salt+"||"+pwd2);
    }
	
	
	  public static String encrytBase64(String source) { 
	        Preconditions.checkArgument(!Strings.isNullOrEmpty(source), "要进行Base64编码操作的数据不能为空"); 
	        byte[] bytes = source.getBytes(); 
	        return Base64.encodeToString(bytes); 
	    }
	  
	   public static String decryptBase64(String cipherText) { 
	        Preconditions.checkArgument(!Strings.isNullOrEmpty(cipherText), "要进行Base64解码操作的数据不能为空"); 
	        return Base64.decodeToString(cipherText); 
	    } 
	    public static String encrytHex(String source) { 
	        Preconditions.checkArgument(!Strings.isNullOrEmpty(source), "要进行Hex编码操作不能为空"); 
	        byte[] bytes = source.getBytes(); 
	        return Hex.encodeToString(bytes); 
	    }
	    public static String decryptHex(String cipherText) { 
	        Preconditions.checkArgument(!Strings.isNullOrEmpty(cipherText), "要进行Hex解码操作数据不能为空"); 
	        return new String(Hex.decode(cipherText)); 
	    } 
	    
	    
	    
}
